#include "frmLogin.h"
#include "frmServerChat.h"
#include "ui_frmServerChat.h"
#include <QCryptographicHash>
#include <KServerChat>
#include <QMap>
QMap<QString,KServerChat*> stringLinkServerChat;
QObject *formSC;

frmServerChat::frmServerChat(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frmServerChat)
{
    setWindowFlags(windowFlags()^Qt::WindowContextHelpButtonHint^Qt::WindowMinMaxButtonsHint);
    ui->setupUi(this);
}

frmServerChat::~frmServerChat()
{
    delete ui;
}

void frmServerChat::closeEvent(QCloseEvent *)
{
    foreach(KServerChat *serverChat, stringLinkServerChat.values())
    {
        serverChat->disconnectChat();
    }
    frmLogin* login = (frmLogin*)formSC;
    login->serverChatTurnedOff();
}

void frmServerChat::setForm(frmLogin* login)
{
    formSC = login;
}

void frmServerChat::on_cmdConnect_clicked()
{
    if (ui->txtIP->text() != "")
    {
        frmLogin *login = (frmLogin*)formSC;
        KServerChat *serverChat = new KServerChat();
        serverChat->setSerial(generateMD5(login->getUserName()));
        bool isConnected = serverChat->connectChat(ui->txtIP->text(),login->getUserName());
        if (isConnected)
        {
            int tabID = ui->twChats->addTab(serverChat,ui->txtIP->text());
            stringLinkServerChat.insert(ui->txtIP->text(),serverChat);
            serverChat->setTabID(tabID);
            serverChat->setTabName(ui->txtIP->text());
            ui->twChats->setCurrentIndex(tabID);
            connect(serverChat,SIGNAL(chatDisconnected()),this,SLOT(isDisconnected()));
            ui->txtIP->clear();
        }
        else
        {
            serverChat->deleteLater();
        }
    }
}

QString frmServerChat::generateMD5(QString value)
{
    return QString::fromUtf8(QCryptographicHash::hash(value.toUtf8(),QCryptographicHash::Md5).toHex().toUpper());
}

void frmServerChat::isDisconnected()
{
    KServerChat *serverChat = (KServerChat*)sender();
    ui->twChats->removeTab(serverChat->getTabID());
    stringLinkServerChat.remove(serverChat->getTabName());
    serverChat->deleteLater();
}

void frmServerChat::on_twServers_itemChanged(QTreeWidgetItem *item, int column)
{
    Q_UNUSED(column);
    ui->txtIP->setText(item->text(1));
}

void frmServerChat::on_twServers_itemSelectionChanged()
{
    on_twServers_itemChanged(ui->twServers->currentItem(),0);
}

void frmServerChat::on_twServers_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    Q_UNUSED(column);
    ui->txtIP->setText(item->text(1));
    on_cmdConnect_clicked();
}

void frmServerChat::on_txtIP_returnPressed()
{
    on_cmdConnect_clicked();
}
